package com.koomii.myproject.web.interceptor;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.koomii.myproject.common.MessageBean;
import com.koomii.common.util.UrlUtils;

/**
 * 公用拦截
 * @author david
 *
 */
public class CommonInterceptor extends HandlerInterceptorAdapter {
	private static final Log log = LogFactory.getLog(CommonInterceptor.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//当前地址
		String uri = request.getRequestURI();
		if("GET".equals(request.getMethod()) && uri.indexOf("/static")==-1) {
			String url = uri;

			Enumeration<String> names = (Enumeration<String>)request.getParameterNames();
			StringBuffer params = new StringBuffer();
			int i=0;
			
			Map<String, String[]> paramMap = request.getParameterMap();
			while(names.hasMoreElements()) {
				String name = names.nextElement();
				//清除来源URL 和 消息
				if(!"returnUrl".equals(name) && !"msg".equals(name)) {
					if(i==0) {
						params.append(name);
						params.append("=");
						params.append(paramMap.get(name)[0]);
					} else {
						params.append("&");
						params.append(name);
						params.append("=");
						params.append(paramMap.get(name)[0]);
					}
					i++;
				}
			}
			if(i!=0) {
				url = uri + "?" + params.toString();
			}
			request.setAttribute("currUrl", url);
		}
		//来源地址
		String returnUrl = request.getParameter("returnUrl");
		
		if(StringUtils.isBlank(returnUrl)) {
			returnUrl = "/home";
		}
		
		request.setAttribute("returnUrl", returnUrl);
		
		//消息报文
		String message = request.getParameter("msg");
		if(StringUtils.isNotBlank(message)) {
			MessageBean msg = processMsg(message);
			if(msg!=null) {
				request.setAttribute("msg", msg);
			}
		}

		return super.preHandle(request, response, handler);
	}
	
	private MessageBean processMsg(String message) {
		MessageBean msg = null;
		try {
			
			if(StringUtils.isNotBlank(message)) {
				message = UrlUtils.urlDecode(message);
				JSONObject obj = JSONObject.fromObject(message);
				String status = obj.get("status")!=null?obj.get("status").toString():null;
				String tip = obj.get("message")!=null?obj.get("message").toString():null;
				
				if(status!=null && tip != null) {
					msg = new MessageBean();
					if("1".equals(status)) {
						msg.fireSuccess();
					} else {
						msg.fireFailed();
					}
					msg.setMessage(tip);
				}
			}
		} catch (Exception e) {
			log.error("convert request msg param error::" + message);
		}
		return msg;
	}

}
